﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using Sustainalytics.ClientDW.DataAccessLayer;
using Sustainalytics.ClientDW.DataAccessLayer.ESGRatings;
using Sustainalytics.DataLayer;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.ESGRatings.BusinessLogic;
using Sustainalytics.ESGRatings.BusinessLogic.Models;
using Sustainalytics.ESGRatings.Service.Models;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using Sustainalytics.Utils;
using System.Web.Http.Cors;

namespace Sustainalytics.ESGRatings.Service.Controllers
{
    using Sustainalytics.DataLayer.EsgRatings;    

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //todo: petre claims checker  miss handles  atachaments, we need to update here [ClaimsChecker("api/v1/company/esg")]
    [RoutePrefix("api/v1/esgratings/keyesgissues")]
    [LogControllerFilter(true, true, false)]
    public class KeyESGIssuesController : ApiController
    {
        private IKeyESGIssuesManagement _keyESGIssuesManagement;
        public KeyESGIssuesController() { }

        public KeyESGIssuesController(KeyEsgIssuesManagement keyESGIssuesManagement)
        {
            _keyESGIssuesManagement = keyESGIssuesManagement;
        }



        [Route("")]
        public HttpResponseMessage Post()
        {
            try
            {
                if (_keyESGIssuesManagement == null)
                {
                    var clientConnectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
                    var connectionStringsManager =
                        ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(clientConnectionString));
                    var clientDwConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);

                    var clientDwRepository = ClientDwRepository.GetInstance(clientDwConnectionString);

                    var esgInputFileRepository = EsgInputFileRepository.GetInstance(new FileRepository(clientConnectionString),
                                                                                    new RepositoryCollection<EsgInputFile>(clientConnectionString));

                    // add KeyESGIssues Repository
                    var keyEsgIssuesRepository = KeyEsgIssuesRepository.GetInstance(clientDwConnectionString);

                    _keyESGIssuesManagement = KeyEsgIssuesManagement.GetInstance(clientDwRepository, esgInputFileRepository, keyEsgIssuesRepository);
                }

                var fileUploadLogs = new FileUploadLogs { Errors = string.Empty };

                if (Request.Content.Headers.ContentDisposition == null)
                {
                    fileUploadLogs.Errors = "No content-disposition provided in the header of the request!";
                }

                if (Request.Content.Headers.ContentType == null)
                {
                    fileUploadLogs.Errors += (fileUploadLogs.Errors.Length > 0 ? Environment.NewLine : string.Empty) +
                                                "No ContentType provided in the header of the request!";
                }

                var keyEsgIssuesFilecontent = Request.Content.ReadAsByteArrayAsync().Result;
                var keyEsgIssuesFileName = Request.Content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                var keyEsgIssuesFileContentType = Request.Content.Headers.ContentType.MediaType;

                fileUploadLogs = _keyESGIssuesManagement.LoadKeyESGIssuesForProcessing(keyEsgIssuesFileName, keyEsgIssuesFilecontent, keyEsgIssuesFileContentType);

                return fileUploadLogs.Errors.Length > 0 ? Request.CreateResponse(HttpStatusCode.BadRequest, new { FileUploadLogs = FileUploadLogsDto.CreateComplete(fileUploadLogs) }) :
                                                            Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                                              new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
        }
    }
}
